#ifndef _K_MEMORY_
#define _K_MEMORY_

namespace krt
{

	typedef struct KRUNTIME_CLASS MEMORY_MANAGER
	{
		void* (*alloc)(size_t);
		void (*free)(void* mem);
		void* (*realloc)(void* mem, size_t);
	}MemoryManager;

	KRUNTIME_CLASS extern MemoryManager DefaultMemoryManager;

	class KRUNTIME_CLASS AutoBuffer
	{
	public:
		inline AutoBuffer(): m_MemMgr(&DefaultMemoryManager), m_buf(NULL), m_len(0){};
		inline AutoBuffer(MemoryManager *mm): m_MemMgr(mm), m_buf(NULL), m_len(0){};

		inline ~AutoBuffer()
		{
			this->free();
		}

		inline void free()
		{
			if (m_buf)
			{
				m_MemMgr->free(m_buf);	
				m_buf = NULL;
				m_len = 0;
			}
		}

		inline void alloc(size_t len)
		{
			if (len != m_len)
			{
				this->free();
				m_buf = m_MemMgr->alloc(len);
				m_len = len;
			}
		}

		inline void* GetBuffer() { return m_buf; }
		inline size_t GetLength() { return m_len; }

		inline void zero()
		{
			memset(m_buf, 0, m_len);
		}

		inline void fill(BYTE v)
		{
			memset(m_buf, v, m_len);
		}

	private:
		MemoryManager *m_MemMgr;
		void *m_buf;
		size_t m_len;
	};

}

#endif	//_K_MEMORY_